package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.kh.KHDBConfig
import cn.com.kh.getProperty
import cn.com.kh.KHUtil
import com.wisdge.utils.RandomUtils
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONObject
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import com.wisdge.dataservice.xhr.XHRPoolService

/**
 *
 * @Title: apiWXMain*
 * @Description:对接微信公众号主接口
 * @author: LJT* @date 2019-12-17 02:28:00
 *
 */

public class apiNGSToken implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiNGSToken.class);
    private static XHRPoolService xhrService = new XHRPoolService();
    String dealSQL = "";

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        // 获取数据源List<Map<String, Object>>
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            log.warn("API被非法IP调用-Request Not Allow!");
            return "Request Not Allow!";
        }

        String dataSourceID = "dataSource";
        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        JSONObject result = new JSONObject();
        JSONObject datatoken = new JSONObject();

        String API_ID = "";

        if (getMethod.equals("GET")) {
            API_ID = KHUtil.FastJsonNull(request.getParameter("appid"));
            log.debug("原始Get请求参数:" + API_ID);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                API_ID += line;
            }
            log.debug("原始Post请求参数:" + API_ID);
        }
        API_ID = KHUtil.isNull(API_ID) ? "NGS" : API_ID;
        log.debug("API_ID请求参数结果:" + API_ID);

        try {
            // 检查当前Token状态
            String selectSQL = "Select Loginuuid From Webloginlist Where Rolegroup_Id = ? And Agent_Id = ? And Clientflag = '1' Limit 1";
            List<Map<String, Object>> selectExits = jt.queryForList(selectSQL, KHDBConfig.getParam(eliteBean, "NG-ROL"), KHDBConfig.getParam(eliteBean, "NG-LOG"));
            if (selectExits.size() > 0) {
                Map selectExitsm = selectExits.get(0);
                String TOKEN = selectExitsm.get("Loginuuid");

                boolean isVToken = checkToken(eliteBean, TOKEN);
                if (isVToken) {
                    result.put("code", 1);
                    result.put("msg", "查询完成");
                    datatoken.put("access_token", TOKEN);
                    result.put("data", datatoken);
                } else {
                    result = getToken(eliteBean);
                }

            } else {
                result = getToken(eliteBean);

            }

        } catch (Exception e) {
            log.error("接口处理异常", e);
            // 失败返回

            result.put("code", -1);
            result.put("msg", e.getMessage());
            result.put("data", datatoken);

        }

        log.debug("Token处理完成返回结果:" + result.toString());

        return result.toString();
    }

    // 用getToken查询
    public static JSONObject getToken(EliteBean eliteBean) {

        JSONObject result = new JSONObject();
        // 调用NGS获取最新Token
        String ngsLoginURL = KHDBConfig.getAPIURL(eliteBean, "SYS_InnerDomain") + "/ngs/login_";

        log.debug("调用API获取最新TokenURL:" + ngsLoginURL);

        ArrayList subProjectList = new ArrayList();
        ArrayList projectArr = new ArrayList();

        JSONObject objPro = new JSONObject();
        objPro.put("dbPool", getProperty.get("NGS.dbPool"));
        objPro.put("prjId", getProperty.get("NGS.prjId"));
        objPro.put("prjName", getProperty.get("NGS.prjName"));
        objPro.put("groupId", KHDBConfig.getParam(eliteBean, "NG-ROL"));

        JSONObject obj = new JSONObject();
        obj.put("standFlag", Integer.valueOf(getProperty.get("NGS.standFlag")));
        obj.put("cacheFlag", Integer.valueOf(getProperty.get("NGS.cacheFlag")));
        obj.put("clientFlag", Integer.valueOf(getProperty.get("NGS.clientFlag")));
        obj.put("useLang", "zh_CN");
        obj.put("epid", getProperty.get("NGS.getTokenEpid"));
        obj.put("remoteInfo", RandomUtils.getGUID());
        obj.put("loginId", KHDBConfig.getParam(eliteBean, "NG-LOG"));
        obj.put("password", KHDBConfig.getParam(eliteBean, "NG-PWD"));
        obj.put("subProjectList", subProjectList);
        projectArr.add(objPro);
        obj.put("projects", projectArr);
        Map loginParams = new HashMap();
        loginParams.put("payload", obj.toString());

        String ngsTokenResult = xhrService.post(ngsLoginURL, loginParams);
        log.debug("调用API获取最新Token返回：" + ngsTokenResult);
        JSONObject wxTokenJson = new JSONObject(ngsTokenResult);

        String code = KHUtil.GetJV(wxTokenJson, "code");
        String msg = KHUtil.GetJV(wxTokenJson, "message");

        JSONObject datatoken = new JSONObject();
        if (code == "1" && !KHUtil.isNull(KHUtil.GetJV(wxTokenJson.getJSONObject("value").getJSONArray("projects").getJSONObject(0), "token"))) {

            String access_token = wxTokenJson.getJSONObject("value").getJSONArray("projects").getJSONObject(0).getString("token");

            result.put("code", 1);
            result.put("msg", "更新完成");
            datatoken.put("access_token", access_token);
            result.put("data", datatoken);

        } else {

            result.put("code", code);
            result.put("msg", msg);
            result.put("data", datatoken);

        }

    }

    /**
     * 验证当前Token是否有效
     * @param eliteBean
     * @param token
     * @return
     */
    public static boolean checkToken(EliteBean eliteBean, String token) {

        // 调用NGS验证Token有效性
        String ngsLoginURL = KHDBConfig.getAPIURL(eliteBean, "SYS_InnerDomain") + "/ngs/token_";


        log.debug("调用API获取验证TokenURL:" + ngsLoginURL);

        Map loginParams = new HashMap();
        loginParams.put("token", token);

        String ngsTokenResult = xhrService.post(ngsLoginURL, loginParams);
        log.debug("调用API获取验证Token返回：" + ngsTokenResult);
        JSONObject wxTokenJson = new JSONObject(ngsTokenResult);

        int code = wxTokenJson.getInt("code");
        String msg = wxTokenJson.getString("message");

        log.debug("调用API获取验证Token信息-【code】:" + code + " 【msg】:" + msg);

        if (code == 1) {
            return true;

        } else {
            return false;

        }

    }
}
